package org.example.netty.test.nio.netty.chat.handler;

import cn.hutool.crypto.digest.MD5;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;
import org.example.netty.test.nio.netty.chat.bean.LoginMessage;
import org.example.netty.test.nio.netty.chat.bean.SystemMessage;
import org.example.netty.test.nio.netty.chat.bean.User;
import org.example.netty.test.nio.netty.chat.common.SystemId;
import org.example.netty.test.nio.netty.chat.common.SystemMessageType;
import org.example.netty.test.nio.netty.chat.common.UserStatus;
import org.example.netty.test.nio.netty.chat.session.GlobalContent;
import org.example.netty.test.nio.netty.chat.session.UserSession;
import org.example.netty.test.nio.netty.chat.util.NettyChannelUtil;

/**
 * @author zp
 * @version 1.0
 * @description: 处理消息LogMessage
 * @date 2023/4/6 18:29
 */
@Slf4j
public class LoginMessageHandler extends SimpleChannelInboundHandler<LoginMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, LoginMessage msg) throws Exception {
        GlobalContent globalContent = GlobalContent.getInstance();
        Channel channel = ctx.channel();
        // 生成用户ID
        String userId = MD5.create().digestHex16(msg.getUserName()+msg.getPassword(), CharsetUtil.UTF_8);
        UserSession userSession = globalContent.getUserSession(userId);
        if(userSession!=null){
            User user = userSession.getUser();
            if(UserStatus.REGISTER_STATUS == user.getStatus()){
                user.setPassword(msg.getPassword());
                user.setUserName(msg.getUserName());
                user.setUserId(userId);
                user.setStatus(UserStatus.LOGIN_STATUS);
                // 设置用户状态
                userSession.setUser(user);
                // 绑定Channel UserSession的关系
                globalContent.bind(user.getUserId(), userSession,channel);
                ctx.channel().attr(SystemId.USER_SESSION_KEY).set(userSession);
                // 脱敏密码
                String replacePassword = NettyChannelUtil.replaceWithAsterisks(msg.getPassword());
                msg.setPassword(replacePassword);
                ctx.channel().writeAndFlush(msg);
            }else if(UserStatus.LOGIN_STATUS == user.getStatus()){
                // 无法重复登入 若已登入报错重复登入
                SystemMessage.sendFailMessage(SystemMessageType.LOG_IN_REPEAT_FAIL,ctx);
            }

        }else {
            SystemMessage.sendFailMessage(SystemMessageType.LOGIN_USER_FAIL,ctx);
        }

    }
}
